package cmd

import (
	"bytes"
	"context"
	"fmt"
	// "net/url"
	// "gitee.com/quantum-force/of-generic/safe"
	"github.com/chromedp/cdproto/cdp"
	"github.com/chromedp/chromedp"
)

// to think:
// var nodes []*cdp.Node
// chromedp.Nodes(nextSel, &nodes, chromedp.AtLeast(0))
// len (nodes) == 0
// 如何整合成一个chromedp.Action or chromedp.ActionFunc
// 1、依赖关联对象TaskRunner
// 2、使用context传值

func (tr *TaskRunner) SearchByKeyworOld(city City, keyword string) *TaskRunner {
	var nodes []*cdp.Node
	var notfoundNodes []*cdp.Node
	var initUrl = fmt.Sprintf(`%s/search/keyword/%s/0_%s`, dpHost, city, keyword)
	tr.tasks = append(tr.tasks,
		chromedp.Navigate(initUrl),
		chromedp.Nodes(`body > div.section.Fix.J-shop-search > div.content-wrap > div.shop-wrap > div.not-found`, &notfoundNodes, chromedp.AtLeast(0)),
		chromedp.ActionFunc(func(ctx context.Context) error {
			if len(notfoundNodes) > 0 {
				return fmt.Errorf("not found any shop for keyword => %s @ %s", keyword, city.String2())
			}
			return nil
		}),
		chromedp.WaitVisible(`#shop-all-list`, chromedp.ByID),

		chromedp.Nodes(`#shop-all-list > ul > li > div.txt > div.tit > a[data-hippo-type]`, &nodes, chromedp.ByQueryAll),
		chromedp.ActionFunc(func(ctx context.Context) error {
			slog.Infof("after shop-all-list...")
			// keyword
			var err error
			page := 1
			if len(nodes) > 0 {
				if err = tr._dumpSearchResultToFile(nodes, fmt.Sprintf("tmp/%s_%s_p%d.txt", city, keyword, page)); err != nil {
					return err
				}
			}
			var nextBtns []*cdp.Node
			var nextSel = `body > div.section.Fix.J-shop-search > div.content-wrap > div.shop-wrap > div.page > a.next`
			if err = chromedp.Run(ctx, chromedp.Nodes(nextSel, &nextBtns, chromedp.AtLeast(0))); err != nil {
				return err
			}
			hasNext := len(nextBtns) > 0
			maxLoopCnt := 199
			for {
				if page > maxLoopCnt {
					fmt.Println("触发无限循环保护,退出for..")
					break
				}
				if !hasNext {
					fmt.Println("已经是查询结果最后一页..")
					break
				}
				// 随机等待 10-30秒
				nextPage := page + 1
				fmt.Printf("随机等待 [10-30]秒进入下一页(%d)..\n", nextPage)
				// 开一个goroutine打印倒计时等待秒数,主线程阻塞
				Countdown(randOver(10, 30))

				if err = chromedp.Run(ctx, chromedp.Tasks{
					chromedp.Navigate(nextBtns[0].AttributeValue("href")),
					chromedp.WaitVisible(`#shop-all-list`, chromedp.ByID),
					chromedp.Nodes(`#shop-all-list > ul > li > div.txt > div.tit > a[data-hippo-type]`, &nodes, chromedp.ByQueryAll),
					chromedp.ActionFunc(func(ctx context.Context) error {
						if len(nodes) > 0 {
							return tr._dumpSearchResultToFile(nodes, fmt.Sprintf("tmp/%s_%s_p%d.txt", city, keyword, nextPage))
						}
						fmt.Printf("当前页(%d)解析完毕..\n", nextPage)
						return nil
					}),
					chromedp.Nodes(nextSel, &nextBtns, chromedp.AtLeast(0)),
				}); err != nil {
					slog.Error("下当前页(%d)处理错误", err)
					return err
				}
				hasNext = len(nextBtns) > 0
				page++
			}

			slog.Infof("SearchByKeyword done...")
			return nil
		}))
	return tr
}

func (tr *TaskRunner) _dumpSearchResultToFile(nodes []*cdp.Node, file string) (err error) {
	bu := new(bytes.Buffer)
	for _, nodePtr := range nodes {
		slog.Infof("href=>%s", nodePtr.AttributeValue("href"))
		bu.WriteString(nodePtr.AttributeValue("href"))
		bu.WriteByte(0x0A) // \n
	}
	tr.srMu.Lock()
	defer tr.srMu.Unlock()
	err = tr.WriteFile(file, bu)
	return
}
